import { WechatyBuilder, ScanStatus, log } from 'wechaty'
import qrTerminal from 'qrcode-terminal'
import { sendMessage } from './message.js'
import fs from 'fs'

/**
 * 扫码
 * @param {*} qrcode 
 * @param {*} status 
 */
function onScan(qrcode, status) {
  if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
    // 在控制台显示二维码
    qrTerminal.generate(qrcode, { small: true })
    const qrcodeImageUrl = ['https://api.qrserver.com/v1/create-qr-code/?data=', encodeURIComponent(qrcode)].join('')
  } else {
    log.info('onScan: %s(%s)', ScanStatus[status], status)
  }
}

/**
 * 登录
 * @param {*} user 
 */
function onLogin(user) {
  console.log(`${user} has logged in`)
  const date = new Date()
  console.log(`Current time:${date}`)
}

/**
 * 登出
 * @param {*} user 
 */
function onLogout(user) {
  console.log(`${user} has logged out`)
}

/**
 * 收到好友请求
 * @param {*} friendship 
 */
async function onFriendShip(friendship) {
  // await friendship.accept()
}

/**
 * 接收到消息
 * @param msg
 */
async function onMessage(msg) {
  await sendMessage(msg, bot)
}

// 初始化机器人
const CHROME_BIN = process.env.CHROME_BIN ? { endpoint: process.env.CHROME_BIN } : {}
export const bot = WechatyBuilder.build({
  name: 'WechatEveryDay',
  // puppet: 'wechaty-puppet-wechat4u', // 基于微信的网页协议接口来控制微信账户
  puppet: 'wechaty-puppet-wechat', // 基于微信的客户端协议接口来控制微信账户
  puppetOptions: {
    uos: true,
    ...CHROME_BIN,
  },
})
// 扫码
bot.on('scan', onScan)
// 登录
bot.on('login', onLogin)
// 登出
bot.on('logout', onLogout)
// 收到消息
bot.on('message', onMessage)
// 添加好友
bot.on('friendship', onFriendShip)
// 错误
bot.on('error', (e) => {
  console.error('程序退出,请重新运行程序：', e)
  bot.stop()
  // 如果 WechatEveryDay.memory-card.json 文件存在，删除
  if (fs.existsSync('WechatEveryDay.memory-card.json')) {
    fs.unlinkSync('WechatEveryDay.memory-card.json')
  }
  process.exit()
})
// 启动微信机器人
function botStart() {
  bot
    .start()
    .then(() => console.log('Start to log in wechat...'))
    .catch((e) => console.error('botStart error：', e))
}
botStart();